package com.golddaymicromall.activity.panicbuying;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.golddaymicromall.activity.panicbuyingconfirmpay.PanicBuyingConfirmPayActivity;
import com.golddaymicromall.adapter.PanicBuyingAdapter;
import com.golddaymicromall.base.BaseActivity;
import com.golddaymicromall.bean.PanicBuyingInfo;
import com.golddaymicromall.rxbus.RxBus;
import com.golddaymicromall.util.ActivityController;
import com.golddaymicromall.util.Log;
import com.golddaymicromall.util.SPUtils;
import com.golddaymicromall.activity.R;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;

import static com.google.common.base.Preconditions.checkNotNull;
            //1.实现Contract接口
public class PanicBuyingActivity extends BaseActivity implements PanicBuyingContract.View {
                //2.Contract.Presenter类型的声明
    PanicBuyingContract.Presenter mPresenter;
    @Bind(R.id.paincbuying_confirmpay_back)
    LinearLayout paincbuying_confirmpay_back;

    @Bind(R.id.panicbuying_listview)
    ListView panicbuyingListview;
    @Bind(R.id.panicbuying_num)
    TextView panicbuyingNum;
    @Bind(R.id.textView2)
    TextView textView2;
    @Bind(R.id.allPrice)
    TextView mAllPrice;
    @Bind(R.id.panicbuying_shifujia)
    TextView mpanicbuyingShifujia;
    @Bind(R.id.bottem)
    LinearLayout bottem;
    @Bind(R.id.qianggouwancheng)
    TextView qianggouwancheng;
    @Bind(R.id.humiaojihua)
    ImageView humiaojihua;


//    3.观察者申明
    private Observable<String> rxBusDataObservable;
    private String customerid;
    private String ids;
    private String count;
    private List<PanicBuyingInfo.DataBean> listFlag;
    private List<PanicBuyingInfo.DataBean> list = new ArrayList<PanicBuyingInfo.DataBean>();
    private PanicBuyingAdapter adapter;
    private float allPrice = 0f;
    private float RealPay; //实付价
    private int num;
    private PanicBuyingInfo panicbuyingInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_panic_buying);
        ButterKnife.bind(this);
        initView();
        getPlusinfo();
    }

    private void initView() {

        customerid = SPUtils.get(this, "Id", "").toString();
        //初始化
        new PanicBuyingPresenter(this);
        //加载数据
        mPresenter.getPanicBuyingInfo(customerid);

    }
      //获取返回值
    @Override
    public void showPanicBuyingInfo(String panicbuying) {
        Log.e("panicbuying", panicbuying);
        panicbuyingInfo = JSON.parseObject(panicbuying, PanicBuyingInfo.class);
        if (panicbuyingInfo.isSuccess()) {

            if (panicbuyingInfo.getCode() == 1) {
                list.addAll(panicbuyingInfo.getData());
                adapter = new PanicBuyingAdapter(list, this);
                panicbuyingListview.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            } else if (panicbuyingInfo.getCode() == 2) {
                //限抢一次
                bottem.setVisibility(View.INVISIBLE);
                qianggouwancheng.setVisibility(View.VISIBLE);
                qianggouwancheng.setText("抢购完毕");
            } else if (panicbuyingInfo.getCode() == 4) {
                //抢购完毕
                bottem.setVisibility(View.INVISIBLE);
                qianggouwancheng.setVisibility(View.VISIBLE);
                qianggouwancheng.setText("抢购完毕");
            }
        } else {
            if (panicbuyingInfo.getCode() == 0) {
                //暂无抢购
                bottem.setVisibility(View.INVISIBLE);
                qianggouwancheng.setVisibility(View.VISIBLE);
                qianggouwancheng.setText("暂无抢购");
            } else if (panicbuyingInfo.getCode() == 3) {
                //资格不足 店铺未激活
                bottem.setVisibility(View.INVISIBLE);
                qianggouwancheng.setVisibility(View.VISIBLE);
                qianggouwancheng.setText("店铺未激活");
            }

        }
    }

    @OnClick({R.id.panicbuying_shifujia, R.id.paincbuying_confirmpay_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.paincbuying_confirmpay_back:
                ActivityController.getInstance().removeActivity(this);
                finish();
                break;
            case R.id.panicbuying_shifujia:
                if (allPrice == 0.0) {
                    Toast.makeText(this, "请选择购买物品的数量,谢谢", Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent toConfirmPay = new Intent(this, PanicBuyingConfirmPayActivity.class);
                toConfirmPay.putExtra("listFlag", (Serializable) listFlag);
                toConfirmPay.putExtra("num", "" + num);
                toConfirmPay.putExtra("allPrice", "" + allPrice);
                toConfirmPay.putExtra("ids", ids);
                toConfirmPay.putExtra("count", count);
                startActivity(toConfirmPay);
                break;

        }
    }

    /**
     * if (!"0".equals(materialBringBackInfo.getRecords()) && !"[]".equals(materialBringBackInfo.getRows().toString())) {
     * infos.addAll(materialBringBackInfo.getRows());
     * adapter.notifyDataSetChanged();
     * } else {
     * SnackbarManager.show(Snackbar.with(MaterialBringBackActivity.this).text("没有更多数据了").duration(1000));
     * }
     * <p>
     * if (materialTypeInfo.isSuccess() && "1".equals(materialTypeInfo.getCode())) {
     */

    @Override
    public void showLoading() {
        super.showLoading();
    }

    @Override
    public void dismissLoading() {
        super.dismissLoading();
    }

    @Override
    public void setPresenter(PanicBuyingContract.Presenter presenter) {
        mPresenter = checkNotNull(presenter);
    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.subscribe();
    }

    @Override
    public void onPause() {
        super.onPause();
        mPresenter.unsubscribe();
    }
     // 4.rxbus的使用
    public void getPlusinfo() {
        rxBusDataObservable = RxBus.get().register("rxbus", String.class);
        rxBusDataObservable
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(rxBusData -> {
                    plusPrice();
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //解除订阅
        mPresenter.unsubscribe();
        RxBus.get().unregister("rxbus", rxBusDataObservable);
    }

    //计算总金额
    public void plusPrice() {
        allPrice = 0f;
        num = 0;
        RealPay = 0f;
        boolean flag = true;
        StringBuffer stringBuffer = new StringBuffer();
        StringBuffer sbCount = new StringBuffer();
        listFlag = new ArrayList<PanicBuyingInfo.DataBean>();
        for (PanicBuyingInfo.DataBean info : list) {
            if (info.flag) {

                allPrice += (float) (Float.valueOf(info.getPrice()) * info.getCount());
                if (info.getCount() != 0) {
                    stringBuffer.append(info.getProductid() + ",");
                    sbCount.append(info.getCount() + ",");
                }
                num++;
                listFlag.add(info);
            }
            if (sbCount.length() != 0) {
                ids = stringBuffer.toString().substring(0, stringBuffer.toString().length() - 1);
                count = sbCount.toString().substring(0, sbCount.toString().length() - 1);
            }
            if (!info.flag)
                flag = false;
        }
        mAllPrice.setText(String.format("%.2f", allPrice) + "");
        panicbuyingNum.setText("共 " + num + " 种商品");
        mpanicbuyingShifujia.setText("结算（" + String.format("%.2f", allPrice) + ")");
    }
}
